package com.example.demo.demo;

import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Project spring-demo
 * @Description DemoLocalDate
 * @Author xiaole
 * @Date 2021/7/12 10:37
 */
public class DemoLocalDate {
    public static void main(String[] args) {
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();
        System.out.println("Date = " + date);
        System.out.println("LocalDate = " + localDate);
        System.out.println(getPastDate(1, "yyyyMMdd"));
    }

    public static String getPastDate(Integer day, String pattern) {
        String format = "";
        if (StringUtils.isEmpty(pattern)) {
            pattern = "yyyy-MM-dd";
        }
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            LocalDate date = LocalDate.now().minusDays(day);
            format = formatter.format(date);
        } catch (Exception e) {
            System.out.println("formatDate, {}"+e);
            return format;
        }
        return format;
    }

}
